package com.sharer.last.handler;

import com.sharer.last.base.enums.ExceptionCode;
import com.sharer.last.base.exception.BusinessException;
import com.sharer.last.base.model.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对Controller层全局异常处理
 *
 * @ClassName ControllerExceptionHandler
 * @Author wangjin
 * @Date 2023/5/5 20:57
 * @Description 捕获异常后，返回json数据类型
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice
public class ControllerExceptionHandler {

    /**
     * 捕获自定义的业务异常
     *
     * @param request 请求
     * @param e       自定义抛出的异常信息
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public R businessExceptionHandler(HttpServletRequest request, BusinessException e) {
        log.error("Request URL : {}, Exception :", request.getRequestURL(), e);
        return R.error(e.getExceptionCode());
    }

    /**
     * 捕获参数校验异常
     *
     * @param request 请求
     * @param e       自定义抛出的异常信息
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException e) {
        log.error("Request URL : {}, Exception :", request.getRequestURL(), e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String            message   = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
        return R.error(ExceptionCode.VALIDATION_ERROR, message);
    }

    /**
     * 捕获其它异常
     *
     * @param request 请求
     * @param e       异常信息
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("Request URL : {}, Exception :", request.getRequestURL(), e);
        return R.error(ExceptionCode.FAIL);
    }
}
